from datetime import datetime

import jwt


class UserToken:

    slat = "1234567890"

    def __init__(self):
        self.token_user_mapping = {}

    @staticmethod
    def __user_info():
        return {
            "user_id": "",
            "user_name": "",
            "login_time": int(datetime.now().timestamp())
        }

    def token_encode(self, user):
        user_info = self.__user_info()
        user_info["user_id"] = user.user_id
        user_info["user_name"] = user.username
        token = jwt.encode(user_info, key=self.slat, algorithm="HS256")
        return token

    def token_decode(self, token):
        try:
            user_info = jwt.decode(token, key=self.slat, algorithms=["HS256"])
        except:
            raise Exception("Invalid token")
        if "user_id" not in user_info and "user_name" not in user_info and "login_time" not in user_info:
            raise Exception("Invalid token")
        return user_info

    def token_delete(self, token):
        self.token_user_mapping.pop(token)


token_tool = UserToken()
